# -*- coding: utf-8 -*- 
"""
@Author: 孟颖
@email: 652044581@qq.com
@date: 2023/4/20 15:52
@desc: 请求参数校验的插件示例
"""

from sanic import Sanic
from sanic.response import json
from sanic import Blueprint
from sanic.views import HTTPMethodView
from sanic_dantic import parse_params, BaseModel, Field, validator

app = Sanic(__name__)

# 注册蓝图
DemoBlueprint = Blueprint('demo', url_prefix='/demo')


class Person(BaseModel):
    name: str = Field(description="name of person")
    age: int = Field(default=18, description="age of person")

    @validator('name')
    def name_validator(cls, val):
        if not val.startswith("/"):
            raise Exception("名字校验失败")


# parse_params装饰器参数支持：query, path, body,form

# FBV 参数校验
@app.route('/example')
@parse_params(query=Person)
async def path_param_examples(request, params):
    print("ctx:", request.ctx.params)
    print("params:", params)
    print("name:", params.name)
    print("age:", params.age)

    return json({"ctx": request.ctx.params, "params": params})

# CBV 参数校验
class SyncTestView(HTTPMethodView):

    @parse_params(query=Person)
    def get(self, request):


        return json({"ctx":"params"})


DemoBlueprint.add_route(SyncTestView.as_view(), "/sync")

app.blueprint(DemoBlueprint)

if __name__ == "__main__":
    app.run(host="localhost", port=8000)
